<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket测试</title>
  <script>
    let ws = null;
    window.onload = () => {
        if ('WebSocket' in window) {
            // 创建websocket连接
            ws = new WebSocket('ws://127.0.0.1:8081/websocket');
            // 成功连接的时候推送一条消息，此时服务端就可以开始推送数据了
            ws.onopen = () => {
                console.log('websocket success---');
                let params = {
                    message:'success',
                    from:'B'
                }
                ws.send(JSON.stringify(params));
            }
            ws.onmessage = (message) => {
                let data = message.data;
                if(data && data!='success'){
                    let li = document.createElement('li');
                    let params = data.split(':');
                    let str = '<p class="headImg">'+params[0]+'</p><p class="">'+params[1]+'</p>'
                    li.innerHTML = str;
                    li.className = 'left-user'
                    document.getElementById('list').appendChild(li);
                }
                
                console.log('get websocket message---', data);
            }
            ws.onerror = () => {
                console.error('websocket fail');
            }
        } else {
            console.error('dont support websocket');
        };
    };

    function send(){
        let message = document.getElementById('message').value;
        console.log(message)
        let params = {
            message,
            to:'A',
            from:'B'
        }
        ws.send(JSON.stringify(params));
        let li = document.createElement('li');
        li.innerText = message;
        li.className = 'right-user'
        document.getElementById('list').appendChild(li);
    }
</script>
<style>
    .list{
        width: 400px;
        border: 1px solid #eeeeee;
        height: 500px;
        background-color: powderblue;
        border-radius: 5px;
        line-height: 40px;
        list-style: none;
        padding: 10px;
    }
    .left-user{
        display: flex;
        align-items: center;
    }
    .headImg{
        border: 1px solid fuchsia;
        margin-right: 10px;
        height: 30px;
        width: 30px;
        border-radius: 5px;
        text-align: center;
        line-height: 30px;
        background-color: fuchsia;
    }
    .right-user{
        text-align: right;
    }
    </style>
</head>
<body>
  <div style="display: flex; align-items: center; line-height: 40px;">
    <p>B：</p>
    <input id="message" value=""/>
    <button onclick="send()" style="margin-left: 10px;">发送</button>
  </div>
  <div>
    <ul id="list" class="list">

    </ul>
  </div>
</body>
</html>